 /* On{X} Script: Send reminder text (SMS) to friend on multiple schedules
  *
  * Base Script Developer: Michael Hearn (refer below URL for details)
  * https://dev.onx.ms/forums/topic/send-sms-at-certain-time-help/#post-3410
  *
  * Updated for Multiple Schedules By: Gaurav Nandwani
  *
  * Description:
  *
  * This rule sets scheduled timers at configurable times to send text
  * message (SMS) at defined time everyday to specified friend.
  * 
  * Usage:
  * 
  * Change the below mentioned variables to define friend, message body
  * & and schedule times:
  * 
  * friend	    - Object containing name and phone number of friend
  *     * name          - Name of the friend
  *     * phoneNumber   - Phone number of the friend
  * messageTemplate	- Template used as message body. Preserve the value
  *                   {TOKEN} as is in the message template. {TOKEN} is 
  *                   replaced (case-sensitive) with schedule name for 
  *                   more giving a personlised touch to the message.
  * reminders       - Reminder schedule times array. You can add multiple
  *                   schedule elements to the array.
  *     * name  - Name of the reminder schedule. This is used to name 
  *               the scheduled timer and should be unique in the 
  *               "reminders" array. This shouldn't contain spaces or 
  *               special characters.
  *     * time  - Time of the reminder schedule. This is time string in 
  *               HH:mm or hh:mm AM/PM format.
  */
  
// Initializing variables

var friend = { name : "wife", phoneNumber : "+1234567890" } ;

// Don't remove {TOKEN} from the below template:
var messageTemplate = "Take your medicines for the {TOKEN}.\nLove U";

// Schedule names should be unique and shouldn't have spaces or special characters
var reminders = [
    {name:"morning",time:"10:00 AM"}, 
    {name:"afternoon",time:"4:00 PM"}, 
    {name:"night",time:"9:30 PM"}];

// Finished Initializing Variables

console.log('Started script: Text ' + friend.name + ' at multiple scheduled times.');

// Function to Parse Time from String Value
function parseTime(timeString) {
    if (timeString === '') {
        return null;
    }

    var time = timeString.match(/^(\d+)(:(\d\d))?\s*((a|(p))m?)?$/i);
    if (time === null) {
        return null;
    }

    var hours = parseInt(time[1], 10);
    if (hours === 12 && !time[6]) {
        hours = 0;
    } 
    else {
        hours += (hours < 12 && time[6]) ? 12 : 0;
    }

    var date = new Date();
    date.setHours(hours);
    date.setMinutes(parseInt(time[3], 10) || 0);
    date.setSeconds(0, 0);
    return date;
}

// Function to set the scheduler
function setSchedule(scheduleName, scheduleTime, phoneNumber, messageText, notificationSubject) {
    console.log('Setting system timer: ' + scheduleName + '.');
    // Set system schedule
    device.scheduler.setTimer({
        name: scheduleName,
        time: startTime.getTime(),
        interval: 'day',
        repeat: true,
        exact: true},
        function(){
            // Send Text Message
            device.messaging.sendSms({
                to: friend.phoneNumber,
                body: messageText
                },
                function (error) {
                    if (error) {
                        console.error('Error sending text message: ' + JSON.stringify(error));
                    }
                }
            );
            // Display Notification
            var notification = device.notifications.createNotification(notificationSubject);
            notification.content = messageText;
            notification.on('click', function() { 
                device.applications.launch('messages');
            });
            notification.show();
            console.log('Texting "' + messageText + '" to ' + friend.name);
        }
    );
}

// Start Creating Schedules
for (i=0; i < reminders.length; i++)
{
    console.log('Creating "' + reminders[i].name + '" schedule for reminding at: ' + reminders[i].time);    
    var now = new Date();
    var startTime = parseTime(reminders[i].time);    
    
    if (startTime === null) {
        console.error('Schedule "' + reminders[i].name + '": Invalid time format: ' + reminders[i].time + '. Expected: HH:mm or hh:mm AM/PM');
        continue; // skip to next reminder
    }
    if (startTime.getTime() < now) {
        startTime.setDate(startTime.getDate() + 1);
    }
    
    // Create a system timer to send message at the same time every day.
    setSchedule (
        "text" + friend.name + "_" + reminders[i].name,         // scheduleName
        startTime.getTime(),                                    // scheduleTime
        friend.phoneNumber,                                     // phoneNumber
        messageTemplate.replace("{TOKEN}", reminders[i].name),  // messageText
        "Reminder sent for " + reminders[i].name                // notificationSubject
    );
}
// Script comleted
console.log('Finished script: Text ' + friend.name + ' at multiple scheduled times.');